package com.sunmouse.toolkit.unzip;

import android.content.Context;

import com.sunmouse.toollib.utils.FileUtils;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created by Administrator on 2017/8/28.
 */
public class ZipUtil {
    /**
     * unzip
     */
    public static boolean unzip(Context context, String fileName, String desDir) {
        try {
            String dirName = fileName.substring(0, fileName.lastIndexOf("."));
            InputStream is = context.getAssets().open(fileName);
            ZipInputStream zis = new ZipInputStream(is);
            ZipEntry mEntry;
            while ((mEntry = zis.getNextEntry()) != null) {
                if (mEntry.isDirectory()) continue;
                int len;
                byte[] b = new byte[4 * 1024];
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(FileUtils.newFile(desDir + "/" + dirName + "/" + mEntry.getName())));
                while ((len = zis.read(b, 0, b.length)) != -1) {
                    bos.write(b, 0, len);
                    bos.flush();
                }
                bos.close();
            }
            zis.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * unzip a file and return an array
     */
    public static ArrayList<String> unzipFile(Context context, String fileName, String desDir) {
        ArrayList<String> outList = new ArrayList<>();
        try {
            String dirName = fileName.substring(0, fileName.lastIndexOf("."));
            InputStream is = context.getAssets().open(fileName);
            ZipInputStream zis = new ZipInputStream(is);
            ZipEntry mEntry;
            while ((mEntry = zis.getNextEntry()) != null) {
                if (mEntry.isDirectory()) continue;
                int len;
                byte[] b = new byte[4 * 1024];
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(FileUtils.newFile(desDir + "/" + dirName + "/" + mEntry.getName())));

                while ((len = zis.read(b, 0, b.length)) != -1) {
                    bos.write(b, 0, len);
                    bos.flush();
                }
                bos.close();
                outList.add(desDir + "/" + mEntry.getName());
            }
            zis.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outList;
    }


}
